package com.bw.common;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MonthUtils {


    public static void main(String[] args) {
        String firstDay = getFirstDay(2023, 10, "yyyy-MM-dd");
        String lastDay = getLastDay(2023, 10, "yyyy-MM-dd");
        System.out.println(firstDay);
        System.out.println(lastDay);
    }
    /**
     * 根据年月获取月初第一天日期
     * @param year
     * @param month
     * @return
     */
    public static String getFirstDay(int year,int month,String format) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month-1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);

        Date startDate = calendar.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String formattedStartDate = sdf.format(startDate);

        return formattedStartDate;
    }


    /**
     * 根据年月获取月末最后一天日期
     * @param year
     * @param month
     * @return
     */
    public static String getLastDay(int year,int month,String format) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month);

        calendar.set(Calendar.DAY_OF_MONTH, 1);

        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date endDate = calendar.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String formattedEndDate = sdf.format(endDate);

        return formattedEndDate;
    }
}
